﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace rossisdead.Mvc.Detergent
{
    /// <summary>
    /// Metadata provider needed when using any attribute that derives from CustomModelMetadataAttribute
    /// as part of a ViewModel. 
    /// 
    /// To use, in the application's Application_Start method, set ModelMetadataProviders.Current to
    /// an instance of this provider.
    /// </summary>
    public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(
            IEnumerable<Attribute> attributes,
            Type containerType,
            Func<object> modelAccessor,
            Type modelType,
            string propertyName)
        {
            var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            foreach (var attr in attributes.OfType<CustomModelMetadataAttribute>())
            {
                attr.Process(modelMetadata);
            }

            return modelMetadata;
        }
    }
}